package com.example.email.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.velocity.VelocityEngineUtils;
import org.springframework.web.bind.annotation.GetMapping;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.InputStream;
import java.util.Date;
import java.util.Map;
import java.util.Properties;

/**
 * @author: dangwen
 * @createDate: 2021/3/11
 */
@Controller
public class EmailSenderController {

    @Autowired
    private JavaMailSender javaMailSender;

//    @Autowired
//    private TemplateEngine templateEngine;
//
//    @Autowired
//    private VelocityEngine velocityEngine;

    @Value("${spring.mail.username}")
    private String from;

    @Value("${spring.mail.password}")
    private String password;

//    private static String[] to = new String[]{"dowin.dang@easemob.com","2075304923@qq.com"};
    private static String[] to = new String[]{"405777610@qq.com"};

    /**
     * 发送一封简单邮件
     */
    @GetMapping("sendSimpleEmail")
    public void sendEmail(){
        System.out.println(from);
        // 构建一个邮件对象
        SimpleMailMessage message = new SimpleMailMessage();
        // 设置邮件主题
        message.setSubject("这是一封测试邮件");
        // 设置邮件发送者，这个跟application.yml中设置的要一致
        message.setFrom(from);
        // 设置邮件接收者，可以有多个接收者，中间用逗号隔开，以下类似
        // message.setTo("10*****16@qq.com","12****32*qq.com");
        message.setTo(to);
        // 设置邮件抄送人，可以有多个抄送人
//        message.setCc("baker.song@easemob.com");
        // 设置隐秘抄送人，可以有多个
        // message.setBcc("7******9@qq.com");
        // 设置邮件发送日期
        message.setSentDate(new Date());
        // 设置邮件的正文
        message.setText("这是测试邮件的正文");
        // 发送邮件
        javaMailSender.send(message);
    }

    /**
     * 发送一封带有附件的邮件
     * 常用方法
     */
    @GetMapping("sendFileEmail")
    public void sendAttachFileMail() {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        // 防止文件名称过长导致的邮件中的附件名称乱码的问题
        System.getProperties().setProperty("mail.mime.splitlongparameters", "false");
        // true表示构建一个可以带附件的邮件对象
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(mimeMessage,true);
            helper.setSubject("这是一封带有附件的测试邮件");
            helper.setFrom(from);
            helper.setTo(to);
            //helper.setCc("37xxxxx37@qq.com");
            //helper.setBcc("14xxxxx098@qq.com");
            helper.setSentDate(new Date());
            helper.setText("这是测试邮件的正文");
            // 第一个参数是自定义的名称，后缀需要加上，第二个参数是文件的位置
            helper.addAttachment("班车时刻表.xlsx",new File("C:\\Users\\hp\\Desktop\\附件：班车时刻表.xlsx"));
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 正文中带图片的邮件
     * @throws MessagingException
     */
    @GetMapping("sendImgEmail")
    public void sendImgResMail() throws MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setSubject("这是一封测试邮件");
        helper.setFrom(from);
        helper.setTo(to);
        helper.setCc("37xxxxx37@qq.com");
        //helper.setBcc("14xxxxx098@qq.com");
        helper.setSentDate(new Date());
        // src='cid:p01' 占位符写法 ，第二个参数true表示这是一个html文本
        helper.setText("<tr> <div class='list-line' style='margin:0px auto;display:block;float:left;'> <td style='text-align:center'></td> <h3 class='list-title' style='font-family:SF Pro Text, SF Pro Icons, Helvetica Neue, Helvetica, Arial, sans-serif;font-style:normal;margin:0;text-align:left;overflow-wrap:break-word;word-break:break-word;width:50%;font-size:0px;font-weight:400;color:rgba(154, 161, 177, 1);line-height:20px;display:block;float:left;-cell;padding-right:8px;vertical-align:middle'> ${columnTitle1}</h3> </td> </div> <div class='list-line' style='margin:0px auto;display:block;float:left;'> <td style='text-align:center'></td> <h3 class='list-title' style='font-family:SF Pro Text, SF Pro Icons, Helvetica Neue, Helvetica, Arial, sans-serif;font-style:normal;margin:0;text-align:left;overflow-wrap:break-word;word-break:break-word;width:50%;font-size:0px;font-weight:400;color:rgba(154, 161, 177, 1);line-height:20px;display:block;float:left;-cell;padding-right:8px;vertical-align:middle'> ${columnTitle1}</h3> </td> </div> </tr> <tr> <div class='list-line' style='margin:0px auto;display:block;float:left;'> <td style='text-align:center'></td> <h3 class='list-title' style='font-family:SF Pro Text, SF Pro Icons, Helvetica Neue, Helvetica, Arial, sans-serif;font-style:normal;margin:0;text-align:left;overflow-wrap:break-word;word-break:break-word;width:50%;font-size:0px;font-weight:400;color:rgba(154, 161, 177, 1);line-height:20px;display:block;float:left;-cell;padding-right:8px;vertical-align:middle'> ${columnTitle1}</h3> </td> </div> <div class='list-line' style='margin:0px auto;display:block;float:left;'> <td style='text-align:center'></td> <h3 class='list-title' style='font-family:SF Pro Text, SF Pro Icons, Helvetica Neue, Helvetica, Arial, sans-serif;font-style:normal;margin:0;text-align:left;overflow-wrap:break-word;word-break:break-word;width:50%;font-size:0px;font-weight:400;color:rgba(154, 161, 177, 1);line-height:20px;display:block;float:left;-cell;padding-right:8px;vertical-align:middle'> ${columnTitle1}</h3> </td> </div> </tr> <tr> <div class='list-line' style='margin:0px auto;display:block;float:left;'> <td style='text-align:center'></td> <h3 class='list-title' style='font-family:SF Pro Text, SF Pro Icons, Helvetica Neue, Helvetica, Arial, sans-serif;font-style:normal;margin:0;text-align:left;overflow-wrap:break-word;word-break:break-word;width:50%;font-size:0px;font-weight:400;color:rgba(154, 161, 177, 1);line-height:20px;display:block;float:left;-cell;padding-right:8px;vertical-align:middle'> ${columnTitle1}</h3> </td> </div> <div class='list-line' style='margin:0px auto;display:block;float:left;'> <td style='text-align:center'></td> <h3 class='list-title' style='font-family:SF Pro Text, SF Pro Icons, Helvetica Neue, Helvetica, Arial, sans-serif;font-style:normal;margin:0;text-align:left;overflow-wrap:break-word;word-break:break-word;width:50%;font-size:0px;font-weight:400;color:rgba(154, 161, 177, 1);line-height:20px;display:block;float:left;-cell;padding-right:8px;vertical-align:middle'> ${columnTitle1}</h3> </td> </div> </tr> <tr> <div class='list-line' style='margin:0px auto;display:block;float:left;'> <td style='text-align:center'></td> <h3 class='list-title' style='font-family:SF Pro Text, SF Pro Icons, Helvetica Neue, Helvetica, Arial, sans-serif;font-style:normal;margin:0;text-align:left;overflow-wrap:break-word;word-break:break-word;width:50%;font-size:0px;font-weight:400;color:rgba(154, 161, 177, 1);line-height:20px;display:block;float:left;-cell;padding-right:8px;vertical-align:middle'> ${columnTitle1}</h3> </td> </div> <div class='list-line' style='margin:0px auto;display:block;float:left;'> <td style='text-align:center'></td> <h3 class='list-title' style='font-family:SF Pro Text, SF Pro Icons, Helvetica Neue, Helvetica, Arial, sans-serif;font-style:normal;margin:0;text-align:left;overflow-wrap:break-word;word-break:break-word;width:50%;font-size:0px;font-weight:400;color:rgba(154, 161, 177, 1);line-height:20px;display:block;float:left;-cell;padding-right:8px;vertical-align:middle'> ${columnTitle1}</h3> </td> </div> </tr> <tr> <div class='list-line' style='margin:0px auto;display:block;float:left;'> <td style='text-align:center'></td> <h3 class='list-title' style='font-family:SF Pro Text, SF Pro Icons, Helvetica Neue, Helvetica, Arial, sans-serif;font-style:normal;margin:0;text-align:left;overflow-wrap:break-word;word-break:break-word;width:50%;font-size:0px;font-weight:400;color:rgba(154, 161, 177, 1);line-height:20px;display:block;float:left;-cell;padding-right:8px;vertical-align:middle'> ${columnTitle1}</h3> </td> </div> <div class='list-line' style='margin:0px auto;display:block;float:left;'> <td style='text-align:center'></td> <h3 class='list-title' style='font-family:SF Pro Text, SF Pro Icons, Helvetica Neue, Helvetica, Arial, sans-serif;font-style:normal;margin:0;text-align:left;overflow-wrap:break-word;word-break:break-word;width:50%;font-size:0px;font-weight:400;color:rgba(154, 161, 177, 1);line-height:20px;display:block;float:left;-cell;padding-right:8px;vertical-align:middle'> ${columnTitle1}</h3> </td> </div> </tr> <tr> <div class='list-line' style='margin:0px auto;display:block;float:left;'> <td style='text-align:center'></td> <h3 class='list-title' style='font-family:SF Pro Text, SF Pro Icons, Helvetica Neue, Helvetica, Arial, sans-serif;font-style:normal;margin:0;text-align:left;overflow-wrap:break-word;word-break:break-word;width:50%;font-size:0px;font-weight:400;color:rgba(154, 161, 177, 1);line-height:20px;display:block;float:left;-cell;padding-right:8px;vertical-align:middle'> ${columnTitle1}</h3> </td> </div> <div class='list-line' style='margin:0px auto;display:block;float:left;'> <td style='text-align:center'></td> <h3 class='list-title' style='font-family:SF Pro Text, SF Pro Icons, Helvetica Neue, Helvetica, Arial, sans-serif;font-style:normal;margin:0;text-align:left;overflow-wrap:break-word;word-break:break-word;width:50%;font-size:0px;font-weight:400;color:rgba(154, 161, 177, 1);line-height:20px;display:block;float:left;-cell;padding-right:8px;vertical-align:middle'> ${columnTitle1}</h3> </td> </div> </tr>",true);
        // 第一个参数指的是html中占位符的名字，第二个参数就是文件的位置
//        helper.addInline("p01",new FileSystemResource(new File("C:\\Users\\hp\\Desktop\\邮箱测试文件\\ruiwen.jfif")));
//        helper.addInline("p02",new FileSystemResource(new File("C:\\Users\\hp\\Desktop\\邮箱测试文件\\yasuo.jfif")));
        javaMailSender.send(mimeMessage);
    }

    /**
     * 发送内容带有thymeleaf模板里定义的格式的邮件
     * @throws MessagingException
     */
//    @GetMapping("hello")
//    public void sendThymeleafMail() throws MessagingException {
//        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
//        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
//        helper.setSubject("这是一封测试邮件");
//        helper.setFrom(from);
//        helper.setTo(to);
////        helper.setCc("37xxxxx37@qq.com");
////        helper.setBcc("14xxxxx098@qq.com");
//        helper.setSentDate(new Date());
//        // 这里引入的是Template的Context
//        Context context = new Context();
//        // 设置模板中的变量
//        context.setVariable("username", "dangwen");
//        context.setVariable("num","690");
//        context.setVariable("salary", "99999");
//        // 第一个参数为模板的名称
//        String process = templateEngine.process("click", context);
//        // 第二个参数true表示这是一个html文本
//        helper.setText(process,true);
//        javaMailSender.send(mimeMessage);
//    }
//
//    /**
//     * 发送带有velocity模板内容的邮件
//     * @throws Exception
//     */
//    @GetMapping("velocity")
//    public void sendTemplateMail() throws Exception {
//        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
//        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
//        helper.setFrom(from);
//        helper.setTo(to);
//        helper.setSubject("主题：模板邮件");
//        Map<String, Object> map = new HashedMap();
//        map.put("username", "didi");
//        String text = VelocityEngineUtils.mergeTemplateIntoString(
//                velocityEngine, "clickByVelocity.vm", "UTF-8", map);
//        helper.setText(text, true);
//        javaMailSender.send(mimeMessage);
//    }

    @GetMapping("sendEml")
    public void sendEmlEmail(){
        Properties properties = new Properties();
        properties.setProperty("mail.transport.protocol", "smtp");   // 使用的协议（JavaMail规范要求）
        properties.setProperty("mail.smtp.host", "smtp.qq.com");   // 发件人的邮箱的 SMTP 服务器地址
        properties.setProperty("mail.smtp.starttls.enable", "true"); // 使用TLS
//        properties.setProperty("mail.smtp.auth", "true");
        properties.setProperty("mail.smtp.port", "587");
        Session session = Session.getDefaultInstance(properties);
        Transport transport = null;
        try {
            transport = session.getTransport();
            System.out.println("----"+from+"----"+password);
            transport.connect(from,password);
            InputStream is = new ClassPathResource("templates/【免费领取】2020中国移动游戏质量白皮书_.eml").getInputStream();
            MimeMessage mimeMessage = new MimeMessage(session,is);
            mimeMessage.setFrom(new InternetAddress(from, "dangwenwen", "UTF-8"));
            mimeMessage.setRecipients(Message.RecipientType.TO, to[0]);
            mimeMessage.setSubject("eml邮件测试", "UTF-8");
            mimeMessage.setSentDate(new Date());
            mimeMessage.saveChanges();
            transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 测试模板
     * @return
     */
    @GetMapping("hello1")
    public String returnThymeleafPage(){
        return "hello";
    }

}
